package easyway.test;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * @author liliangwen
 * @date May 9, 2009
 */
public class EJBLookup {

	private static Map icache = new HashMap();
	private static Properties prop = null;

	@SuppressWarnings("unchecked")
	public static Object getEJBRemote(Class sessionbean) throws NamingException {

		try {
			if (prop == null) {
				InputStream is = EJBLookup.class
						.getClassLoader()
						.getResourceAsStream(
								"easyway/test/ejblookup.properties");
				prop = new Properties();
				prop.load(is);
			}
			Object obj = null;

			if (icache.get(sessionbean.getName()) == null) {
				Context ctx = new InitialContext(prop);
				obj = ctx.lookup(prop.getProperty("appName") + "/"
						+ sessionbean.getSimpleName() + "/"
						+ prop.getProperty("interface"));
				System.out.println(prop.getProperty("appName") + "/"
						+ sessionbean.getSimpleName() + "/"
						+ prop.getProperty("interface"));
				synchronized (icache) {
					icache.put(sessionbean.getName(), obj);
				}
				return obj;
			}

			return icache.get(sessionbean.getName());

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;

	}

}
